package tds.model22;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;

/**
 * @Company 杭州先锋电子技术股份有限公司
 * @ClassName Client
 * @Description TODO（这里用一句话描述这个类的作用)
 * @author tds
 * @Date 2020/2/5 22:40
 * @version 1.0.0
 */
public class Client3 {
    public static void main(String[] args) throws Exception {

        Singleton1 singleton1 = Singleton1.getInstance();

        //通过反序列化破解单例模式
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        byte[] bytes = null;

        try{
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);

            oos.writeObject(singleton1);
            bytes = bos.toByteArray();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(oos != null){
                oos.close();
            }
        }

        try{
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
            ois = new ObjectInputStream(bis);
            Singleton1 s1 = (Singleton1) ois.readObject();
            System.out.println(s1 == singleton1);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(ois != null){
                ois.close();
            }
        }

        // 防止反序列化方法
        // 通过添加readResove方法修改反序列化返回的对象
        Singleton6 singleton6 = Singleton6.getInstance();

        try{
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);

            oos.writeObject(singleton6);
            bytes = bos.toByteArray();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(oos != null){
                oos.close();
            }
        }

        try{
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
            ois = new ObjectInputStream(bis);
            Singleton6 s1 = (Singleton6) ois.readObject();
            System.out.println(s1 == singleton6);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(ois != null){
                ois.close();
            }
        }
    }
}
